package com.sxt.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.sxt.system.common.ActiveUser;
import com.sxt.system.common.Constast;
import com.sxt.system.common.DataGridView;
import com.sxt.system.common.LoginToken;
import com.sxt.system.common.tree.TreeNode;
import com.sxt.system.domain.LogInfo;
import com.sxt.system.domain.Menu;
import com.sxt.system.domain.User;
import com.sxt.system.service.LogInfoService;
import com.sxt.system.service.MenuService;
import com.sxt.system.utils.AppWebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author 雷哥
 * @Date 2020/3/5 17:04
 */
@RestController
@RequestMapping(Constast.API+"login")
public class LoginController extends BaseController{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MenuService menuService;

    @Autowired
    private LogInfoService logInfoService;
    /**
     * 做登陆
     */
    @RequestMapping("doLogin")
    public LoginToken login(String username, String password, String key, String captcha, HttpServletRequest request){

//        if(StringUtils.isNotBlank(key)||StringUtils.isNotBlank(captcha)){
//            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
//            String redisVlaue=opsForValue.get(key);
//            if(null!=redisVlaue&&captcha.equalsIgnoreCase(redisVlaue)){
                //组装token
                UsernamePasswordToken token=new UsernamePasswordToken(username,password);
                Subject subject = SecurityUtils.getSubject();
                try {
                    subject.login(token);
                    Serializable webToken = subject.getSession().getId();

                    System.out.println(webToken);

                    //写入登陆日志
                    LogInfo logInfo=new LogInfo();
                    logInfo.setLogintime(new Date());
                    logInfo.setLoginname(AppWebUtils.getCurrentUser().getLoginname()+"--"+AppWebUtils.getCurrentUser().getName());
                    logInfo.setLoginip(request.getRemoteAddr());
                    logInfoService.save(logInfo);
                    return new LoginToken(0,"登陆成功",webToken);
                }catch (Exception e){
                    log.warn("用户名或密码不正确",e);
                    return new LoginToken(-1,"用户名或密码不正确",null);
                }
//            }else {
//                return  new LoginToken(-1,"验证码不正确",null);
//            }
//        }else{
//            return  new LoginToken(-1,"验证码不正确",null);
//        }
    }


    /**
     * 验证码的处理
     */
    @RequestMapping("captcha")
    public void captcha(String key, HttpServletResponse response) throws IOException {
        //使用hutool生成一个验证码
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 38, 4, 4);
//ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
//图形验证码写出，可以写出到文件，也可以写出到流
        //保存到Redis
        if(StringUtils.isNotBlank(key)){
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            opsForValue.set(key,captcha.getCode());
            RedisOperations<String, String> operations = opsForValue.getOperations();
            //设置60秒过期
            operations.expire(key,60, TimeUnit.SECONDS);
            captcha.write(response.getOutputStream());
        }else{
            log.error("验证码的key不能为空login/captcha");
        }
    }


    /**
     * 加载用户的菜单数据
     *
     */
    @RequestMapping("loadIndexMenuJson")
    public DataGridView loadIndexMenuJson(){
        //1,得到当前用户是什么类型
        ActiveUser activeUser= (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        if(null!=activeUser){//如果activerUser为空说明当前访问者没有登陆
            List<Menu> menuList=null;
            //2,如果是超级管理员
            User user=activeUser.getUser();
            Menu menu=new Menu();
            menu.setType(Constast.TYPE_MENU);
            menu.setAvailable(Constast.AVAILABLE_TRUE);
            if(user.getType().equals(Constast.USER_ADMIN)){
                menuList=menuService.queryAllMenuForList(menu);
            }else{
                menuList=this.menuService.queryeMenuByUserIdForList(menu,user.getId());
            }
            List<TreeNode> treeNodes=new ArrayList<>();
            for (Menu m : menuList) {
                Boolean spread=m.getSpread()==Constast.SPREAD_TRUE?true:false;
                treeNodes.add(new TreeNode(m.getId(),m.getPid(),m.getTitle(),m.getIcon(),m.getHref(),m.getTarget(),spread));
            }
            return new DataGridView(TreeNode.TreeNodeBuilder.build(treeNodes,0));
        }else{
            return new DataGridView(-1,null);
        }
    }
}
